package me.sdau.spider.openapi.configs;

import com.google.gson.Gson;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import me.sdau.spider.openapi.service.TokenAuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

/**
 * jwt token 校验类， 验证成功后设置进去SecurityContext中
 */
@Slf4j
@Component
public class JWTAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private TokenAuthenticationService tokenAuthenticationService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        try {
            Optional<Authentication> authentication = tokenAuthenticationService.getAuthentication(request);
            log.debug("VerifyTokenFilter result:[{}]", authentication.orElse(null));
            SecurityContextHolder.getContext().setAuthentication(authentication.orElse(null));
            System.out.println(request.getRequestURI());
        } catch (JwtException e) {
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().println(new Gson().toJson("token 过期或错误,请从新获取 token"));
            log.warn("token 错误/过期 ==> [{}]", e.getMessage(), e);
            return;
        }

        chain.doFilter(request, response);
    }
}
